<template>
	<u-upload
		:fileList="fileList"
		@afterRead="afterRead"
		@delete="deletePic"
		@beforeRead="beforeRead"
		name="1"
		:multiple="multiple"
		:maxCount="maxCount"
		:accept="accept"
		:capture="capture"
		:camera="camera"
		:maxSize="maxSize"
		:useBeforeRead="true"
		:previewFullImage="true"
	></u-upload>
</template>

<script setup lang="ts" name="UploadImage">
/**
 * UploadImage 上传插件
 * @description 支持图片/视频等
 * @property {Array} list 回显图片 [{url: 'https://cdn.uviewui.com/uview/swiper/1.jpg'}]
 * @property {Boolean} multiple = [true | false] 是否支持多选
 * @property {Number} maxCount = 10 最大上传个数
 * @property {String} accept = [image | video | file...] 上传类型
 * @property {String} capture = [camera | album] 上传方式 文件|拍照
 * @property {String} camera = [back | front] 摄像头设置
 * @event {Function} fileChange fileList更新事件
 * @example <upload-image @fileChange="getImages" :list="umodel.images"></upload-image>
 */
import { ref, toRefs } from 'vue';
const emit = defineEmits(['fileChange']);

const props = defineProps({
	list: {
		type: Array,
		default() {
			return [];
		}
	},
	multiple: {
		type: Boolean,
		default: true
	},
	maxCount: {
		type: Number,
		default: 10
	},
	accept: {
		type: String,
		default: 'image'
	},
	capture: {
		type: [String, Array],
		default: 'camera'
	},
	camera: {
		type: String,
		default: 'back'
	},
	maxSize: {
		type: Number,
		default: Number.MAX_VALUE
	},
});

const { list, capture, camera, accept, multiple, maxCount, maxSize } = toRefs(props);

const uploadApi = process.env.VITE_APP_UPLOAD_API;

const folderName = ref('demo');

const fileList = ref(list.value || []);

// 删除图片
const deletePic = (event) => {
  fileList.value.splice(event.index, 1);
  emit('fileChange', fileList.value)
};

// 读取图片
const beforeRead = (event) => {
	// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
	const lists = [].concat(event.file);
	lists.map((item) => {
		if (item.size > maxSize.value) {
			uni.showToast({
				title: `文件不能超过${maxSize.value / 1024 / 1024}M`,
				icon: 'none'
			})
		}
	})
}

// 新增图片
const afterRead = async (event) => {
  // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
  let lists = [].concat(event.file);
  let fileListLen = fileList.value.length;
  lists.map((item) => {
    fileList.value.push({
      ...item,
      status: 'uploading',
      message: '上传中',
    });
  });
  for (let i = 0; i < lists.length; i++) {
	try{
		const result = await uploadFilePromise(lists[i].url);
		let item = fileList.value[fileListLen];
		fileList.value.splice(fileListLen, 1, {
		  ...item,
		  status: 'success',
		  message: '',
		  url: `${uploadApi}/system/fileCenter/preview/${folderName.value}/${result.fileName}`,
		});
		fileListLen++;
	}catch(e){
		// 上传失败，提示用户
		uni.showToast({
			title: e,
			icon: "none"
		})
		fileList.value.splice(fileListLen, 1);
		fileListLen++;
	}
  }
  emit('fileChange', fileList.value)
};

const uploadFilePromise = (url: string) => {
  return new Promise((resolve, reject) => {
    let a = uni.uploadFile({
      url: `${uploadApi}/system/fileCenter/uploadFile/${folderName.value}`, // 仅为示例，非真实的接口地址
      filePath: url,
      name: 'file',
      formData: {
        user: 'test',
      },
      success: (res) => {
		const result = JSON.parse(res.data)
		if (result.code === 200) {
			resolve(result.data);
		} else {
			reject(result.message)
		}
      },
    });
  });
};
</script>